package com.qf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.dto.QfCourse;
import com.qf.pojo.resVo.BaseResult;
import com.qf.service.QFSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class QfSearchServiceImpl implements QFSearchService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public BaseResult search(String keyword,Integer page,Integer size,String sort) {
        //搜索查询
        SearchRequest searchRequest = new SearchRequest("qf-live");
        searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //加入分页
        searchSourceBuilder.from((page-1)*size);
        searchSourceBuilder.size(size);
        //加入高亮展示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //加入前缀 后缀
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("courseName");
        highlightBuilder.field("courseDescription");
        searchSourceBuilder.highlighter(highlightBuilder);
        if (keyword.equals("null")){
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        }else {
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keyword,"courseName","courseDescription","users").field("courseName",10).field("courseDescription",5));
        }
        if (!StringUtils.isEmpty(sort)){
            if (sort.equals("desc")){
                searchSourceBuilder.sort("pay", SortOrder.DESC);
            }
            if (sort.equals("asc")){
                searchSourceBuilder.sort("pay", SortOrder.ASC);
            }

        }
        searchRequest.source(searchSourceBuilder);
        BaseResult baseResult = new BaseResult();
        try {
            SearchResponse search = client.search(searchRequest);
            SearchHits hits = search.getHits();
            baseResult.setTotal(hits.getTotalHits());
            SearchHit[] hits1 = hits.getHits();
            List list = new ArrayList<>();

            for (SearchHit hit:hits1
                 ) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                //解析高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField courseName = highlightFields.get("courseName");
                if (courseName!=null){
                    Text[] fragments = courseName.getFragments();
                    StringBuffer stringBuffer = new StringBuffer();
                    if (fragments!=null){
                        for (Text text:fragments
                             ) {
                            stringBuffer.append(text);
                        }
                    }
                    sourceAsMap.put("courseName",stringBuffer.toString());
                }
                HighlightField courseDescription = highlightFields.get("courseDescription");
                if (courseDescription!=null){
                    Text[] fragments = courseDescription.getFragments();
                    StringBuffer stringBuffer = new StringBuffer();
                    if (fragments!=null){
                        for (Text text:fragments
                        ) {
                            stringBuffer.append(text);
                        }
                    }
                    sourceAsMap.put("courseDescription",stringBuffer.toString());
                }

                //转json
                String s = JSONObject.toJSONString(sourceAsMap);
                QfCourse qfCourse = JSONObject.parseObject(s, QfCourse.class);
                list.add(qfCourse);
            }
            baseResult.setData(list);
            baseResult.setCode(1);
            baseResult.setMsg("查询成功！");
            return baseResult;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new BaseResult(0,"查询失败",null,null);
    }
}
